package com.liujit.validator.utils;

import com.liujit.validator.domain.ValidResult;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author: liujun
 * @date: 2021/6/18 1:11 下午
 * @description: 验证工具类
 */
public class ValidUtil {

    private static Validator validator;

    static {
        validator = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory()
                .getValidator();
    }

    /**
     * 校验对象
     *
     * @param obj      bean
     * @param groups 校验组
     * @return
     * @author: liujun
     * @date: 2021/6/18 1:14 下午
     */
    public static <T> ValidResult validateBean(T obj, Class<?>... groups) {
        ValidResult result = new ValidResult();
        Set<ConstraintViolation<T>> violationSet = validator.validate(obj, groups);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(violation.getPropertyPath().toString(), violation.getMessage());
            }
        }
        return result;
    }

    /**
     * 校验bean的某一个属性
     *
     * @param obj          bean
     * @param propertyName 属性名称
     * @return
     * @author: liujun
     * @date: 2021/6/18 1:14 下午
     */
    public static <T> ValidResult validateProperty(T obj, String propertyName) {
        ValidResult result = new ValidResult();
        Set<ConstraintViolation<T>> violationSet = validator.validateProperty(obj, propertyName);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(propertyName, violation.getMessage());
            }
        }
        return result;
    }
}
